package com.hou.elasticsearch.config;

import org.elasticsearch.client.transport.TransportClient;
import org.elasticsearch.common.settings.Settings;
import org.elasticsearch.common.transport.TransportAddress;
import org.elasticsearch.transport.client.PreBuiltTransportClient;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

import java.net.InetAddress;
import java.net.UnknownHostException;

/**
 * ES配置
 */
@Configuration
public class ElasticSearchConfig {

    //注入配置文件连接属性
    @Value("${elasticsearch.cluster1.ip}")
    private String fristIp;
    @Value("${elasticsearch.cluster1.port}")
    private String fristPort;
    @Value("${elasticsearch.cluster2.ip}")
    private String secondIp;
    @Value("${elasticsearch.cluster2.port}")
    private String secondPort;
    @Value("${elasticsearch.cluster3.ip}")
    private String thirdIp;
    @Value("${elasticsearch.cluster3.port}")
    private String thirdPort;
    @Value("${elasticsearch.clusterName}")
    private String clusterName;

    //配置客户端
    @Bean
    public TransportClient transportClient() {
        TransportClient transportClient = null;
        try {
            //es集群连接
            TransportAddress node = new TransportAddress(
                    InetAddress.getByName(fristIp), Integer.parseInt(fristPort));
            TransportAddress node1 = new TransportAddress(
                    InetAddress.getByName(secondIp), Integer.parseInt(secondPort));
            TransportAddress node2 = new TransportAddress(
                    InetAddress.getByName(thirdIp), Integer.parseInt(thirdPort));
            //es集群配置（自定义配置） 连接自己安装的集群名称
            Settings settings = Settings.builder()
                    .put("cluster.name", clusterName)
                    .put("thread_pool.search.size", Integer.parseInt("5"))//增加线程池个数，暂时设为5
                    .build();
            transportClient = new PreBuiltTransportClient(settings);
            transportClient.addTransportAddress(node);//添加节点
            transportClient.addTransportAddress(node1);
            transportClient.addTransportAddress(node2);
        } catch (UnknownHostException e) {
            e.printStackTrace();
        }
        return transportClient;
    }
}
